<script setup lang="ts">
import { h, ref, reactive, onMounted, computed } from 'vue'
import { NModal, NCard, NForm, NSpace, NFormItem, NInput, NSelect, NAutoComplete, NButton, NDataTable, NPagination, NPopconfirm, useNotification } from 'naive-ui'
import type { FormInst, DataTableColumns } from 'naive-ui'
import http from '@/tools/http'
import { useUserStore } from '@/stores/userStore'

const userStore = useUserStore()

type RowData = {
    paramCode?: string
    paramGroup?: string
    paramName?: string
    paramValue?: string
    remark?: string
}

const paramsTableColumns: DataTableColumns<RowData> = [
    {
        title: "参数编码",
        key: "paramCode",
        width: 200,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "参数名称",
        key: "paramName",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "参数值",
        key: "paramValue",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "参数分组",
        key: "paramGroup",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "备注",
        key: "remark",
        width: 100,
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作",
        key: "actions",
        width: 132,
        fixed: 'right',
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    userStore.hasAuth("params:edit") ? h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openEditParams(rowData)
                        },
                        { default: () => "编辑" }
                    ) : null,
                    userStore.hasAuth("params:delete") ? h(
                        NPopconfirm,
                        {
                            onPositiveClick: (e: MouseEvent) => deleteParams()
                        },
                        {
                            trigger: () => {
                                return h(
                                    NButton,
                                    {
                                        size: "small",
                                        onclick: () => openDeleteParams(rowData)
                                    },
                                    { default: () => "删除" }
                                )
                            },
                            default: () => { return "确认删除该参数？" }
                        }
                    ) : null
                ]
            )
        }
    }
]

const paramsData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const paramsSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    paramCode: null,
    paramName: null,
    paramGroup: null
})

let paramsSearchFormGroupOptions = reactive<any>([])

onMounted(() => {
    pageParams()
    queryParamsGroup()
})

const visiable = ref<boolean>(false)
const title = ref<string>("")
const formRef = ref<FormInst | null>(null)
const formData = reactive<RowData>({
    paramCode: "",
    paramGroup: "",
    paramName: "",
    paramValue: "",
    remark: ""
})

const formParamsGroupOptions = computed(() => {
    return paramsSearchFormGroupOptions.filter((option: any) => {
        if (formData.paramGroup && formData.paramGroup !== "") {
            return option.label.includes(formData.paramGroup)
        }
        return false
    })
})

const formRules = {
    paramCode: {
        required: true,
        message: '请输入参数编码',
        trigger: ['input']
    },
    paramName: {
        required: true,
        message: '请输入参数名称',
        trigger: ['input']
    },
    paramValue: {
        required: true,
        message: '请输入参数值',
        trigger: ['input']
    }
}

function pageNumChange(pageNum: number) {
    paramsSearchFormValue.pageNum = pageNum
    pageParams()
}

function pageSizeChange(pageSize: number) {
    paramsSearchFormValue.pageSize = pageSize
    pageParams()
}

function openAddParams() {
    visiable.value = true
    title.value = "添加参数"
    formData.paramCode = ""
    formData.paramGroup = ""
    formData.paramName = ""
    formData.paramValue = ""
    formData.remark = ""
}

function openEditParams(row: any) {
    visiable.value = true
    title.value = "编辑参数"
    formData.paramCode = row.paramCode
    formData.paramGroup = row.paramGroup
    formData.paramName = row.paramName
    formData.paramValue = row.paramValue
    formData.remark = row.remark
}

function openDeleteParams(row: any) {
    formData.paramCode = row.paramCode
    formData.paramGroup = row.paramGroup
    formData.paramName = row.paramName
    formData.paramValue = row.paramValue
    formData.remark = row.remark
}

function submit() {
    formRef.value?.validate((errors) => {
        if (!errors) {
            if (title.value === "添加参数") {
                addParams()
            } else {
                updateParams()
            }
            visiable.value = false
        }
    })
}

function pageParams() {
    http.post("/params/page", paramsSearchFormValue).then(({ data }) => {
        paramsData.pageNum = data.data.pageNum
        paramsData.pageSize = data.data.pageSize
        paramsData.pages = data.data.pages
        paramsData.total = data.data.total
        paramsData.list.length = 0
        for (let i = 0; i < data.data.list.length; i++) {
            paramsData.list.push(data.data.list[i])
        }
    })
}

function queryParamsGroup() {
    http.post("/params/group/query-all").then(({ data }) => {
        paramsSearchFormGroupOptions.length = 0
        for (let i = 0; i < data.data.length; i++) {
            paramsSearchFormGroupOptions.push({
                label: data.data[i], value: data.data[i]
            })
        }
    })
}

const notification = useNotification()

function addParams() {
    http.post("/params/add", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '添加成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageParams()
            queryParamsGroup()
        }
    })
}

function updateParams() {
    http.post("/params/update", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '修改成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageParams()
            queryParamsGroup()
        }
    })
}

function deleteParams() {
    http.post("/params/delete", formData).then(({ data }) => {
        if (data.code === "0") {
            notification['success']({
                content: '删除成功',
                meta: `${data.msg}`,
                duration: 2500,
                keepAliveOnHover: true
            })
            pageParams()
            queryParamsGroup()
        }
    })
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="paramsSearchFormValue" inline label-placement="left">
                <n-form-item label="参数编码" path="paramCode">
                    <n-input v-model:value="paramsSearchFormValue.paramCode" placeholder="请输入参数编码" clearable />
                </n-form-item>
                <n-form-item label="参数名称" path="paramName">
                    <n-input v-model:value="paramsSearchFormValue.paramName" placeholder="请输入参数名称" clearable />
                </n-form-item>
                <n-form-item label="参数分组" path="paramGroup">
                    <n-select style="width:196px" v-model:value="paramsSearchFormValue.paramGroup"
                        :options="paramsSearchFormGroupOptions" placeholder="请选择参数分组" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageParams()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button v-if="userStore.hasAuth('params:add')" attr-type="button" @click="openAddParams()">新增</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scroll-x="732" :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :columns="paramsTableColumns" :data="paramsData.list" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="paramsData.pageNum" :page-size="paramsData.pageSize"
                :item-count="paramsData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="visiable">
        <n-card style="width: 400px" :title="title">
            <n-form ref="formRef" :model="formData" :rules="formRules" label-width="78px" label-placement="left"
                require-mark-placement="left">
                <n-form-item label="参数编码" path="paramCode">
                    <n-input v-model:value="formData.paramCode" :disabled="title === '编辑参数'" placeholder="请输入参数编码" />
                </n-form-item>
                <n-form-item label="参数名称" path="paramName">
                    <n-input v-model:value="formData.paramName" placeholder="请输入参数名称" />
                </n-form-item>
                <n-form-item label="参数值" path="paramValue">
                    <n-input v-model:value="formData.paramValue" placeholder="请输入参数值" />
                </n-form-item>
                <n-form-item label="参数分组" path="paramGroup">
                    <n-auto-complete v-model:value="formData.paramGroup" :options="formParamsGroupOptions"
                        placeholder="请输入参数分组" clearable />
                </n-form-item>
                <n-form-item label="备注" path="remark">
                    <n-input v-model:value="formData.remark" placeholder="请输入备注" />
                </n-form-item>
            </n-form>
            <template #footer>
                <n-space justify="end">
                    <n-button attr-type="button" @click="visiable = false">取消</n-button>
                    <n-button attr-type="button" @click="submit()">提交</n-button>
                </n-space>
            </template>
        </n-card>
    </n-modal>
</template>

<style scoped>
.display-flex-end {
    display: flex;
    width: 100%;
    justify-content: flex-end;
}
</style>